package db

import (
	"encoding/json"
	"errors"
)

//timeout: seconed
// 读cache: Cache("111", nil, 0, &dstResult)

func Cache(key string, val interface{}, timeout int, dst interface{}) error {
	if cdb == nil || len(key) == 0 {
		return errors.New("cdb is nil or len(key) == 0")
	}

	ckey := cacheKey(CBD_CACHE, []byte(key))

	if val == nil {
		if dst == nil {
			return errors.New("dst is nil")
		}
		data, err := cdb.Get(ckey, ro)
		if err != nil {
			return err
		}
		err = json.Unmarshal(data, dst)
		if err != nil {
			return err
		}
	} else {
		data, err := json.Marshal(val)
		if err != nil {
			return err
		}
		err = cdb.Put(ckey, data, wo)
		if err != nil {
			return err
		}
	}

	return nil
}
